package com.itheima.reggie.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 文件上传、下载公共类
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    //定义一个根目录
    @Value("${reggie.path}")
    private String root;

    /*  *//**
     * 文件上传
     *
     * @param file
     * @return
     *//*
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("文件上传中。。。。。");
        log.info("file={}", file.toString());
        String originalFilename = file.getOriginalFilename();
        //name表示后缀名
        String name = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接一个新的文件名
        String fileName = UUID.randomUUID().toString() + name;
        //创建一个目录对象
        File dir = new File(root);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //文件上传
            dir.mkdirs();
        }
        //把上传的图片临时储存到某个指定的文件夹中，最后再以流的方式去写回到浏览器中展示
        try {
            file.transferTo(new File(root + fileName));

        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);

    }


    @GetMapping("/download")
    public String download(String name, HttpServletResponse response ,String url) {
        log.info("文件下载中。。。。。");
        try {
            //输入流，用来读取刚刚指定的临时目录的图片
            FileInputStream fis = new FileInputStream(new File(root + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream os = response.getOutputStream();
            //设置一下输出流文件的格式
            response.setContentType("image/jpeg");
            //循环写到浏览器中

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }

            //关闭流
            fis.close();
            os.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;

    }*/




    /*文件上传*/
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //原始文件名
        String originalFilename = file.getOriginalFilename(); //abc.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") );
        //使用UID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString()+suffix;  //dfsdfdfd.jpg


        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-nanjing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tJgsyNcCnKULCiiGHzM";
        String accessKeySecret = "LvbG3MDUTGRUIzUxMLqBxKTI9p8f9W";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "reggie-takeoutcmy";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        //String objectName = "images/"+fileName;
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, file.getInputStream());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return R.success(fileName);
    }

    /*文件下载*/
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        log.info("请求下载文件地址:" + name);
        //设置回传格式
        response.setContentType("image/jpeg");

        //对象存储
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-nanjing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tJgsyNcCnKULCiiGHzM";
        String accessKeySecret = "LvbG3MDUTGRUIzUxMLqBxKTI9p8f9W";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "reggie-takeoutcmy";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。

        //String objectName = "images/" + name;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
        OSSObject ossObject = ossClient.getObject(bucketName, name);
        // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
        InputStream content = ossObject.getObjectContent();

        //输入流读取文件
        int len;
        byte[] bytes = new byte[1024];
        ServletOutputStream outputStream = response.getOutputStream();
        //输出流返回给页面
        while ((len = content.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        outputStream.close();
        content.close();
        // 关闭OSSClient。
        ossClient.shutdown();
    }
}


